﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MyMvcClientOne.Models;
using Newtonsoft.Json.Linq;
using Serilog;

namespace MyMvcClientOne.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        readonly IDiagnosticContext _diagnosticContext;
        public HomeController(ILogger<HomeController> logger,IDiagnosticContext diagnosticContext)
        {
            _logger = logger;
            _diagnosticContext = diagnosticContext ??
                throw new ArgumentNullException(nameof(diagnosticContext));
        }

        public IActionResult Index()
        {
            _diagnosticContext.Set("MySerilog", 10001);
            _logger.LogInformation("start index.");
            return View();
        }

        public IActionResult Privacy()
        {
            string apples = 1.ToString();
            string pears = 2.ToString();
            string bananas = 3.ToString();

            _logger.Log(LogLevel.Error,MyLogEvents.Privacy,"Parameters: {pears}, {bananas}, {apples}", apples, pears, bananas);
            // The request completion event will carry this property
            _diagnosticContext.Set("CatalogLoadTime", 1423);
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult Logout()
        {
            return SignOut("Cookies", "oidc");
        }

        public async Task<IActionResult> CallApi()
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");
            var refresh = HttpContext.GetTokenAsync("refresh_token");

            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var content = await client.GetStringAsync("http://localhost:6001/api/myidentity");

            ViewBag.Json = JArray.Parse(content).ToString();
            return View("json");
        }
    }

    public class MyLogEvents
    {
        public const int Privacy = 5000;
        public const int GenerateItems = 1000;
        public const int ListItems = 1001;
        public const int GetItem = 1002;
        public const int InsertItem = 1003;
        public const int UpdateItem = 1004;
        public const int DeleteItem = 1005;

        public const int TestItem = 3000;

        public const int GetItemNotFound = 4000;
        public const int UpdateItemNotFound = 4001;
    }
}
